package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.Null;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ArticleController
 * @Description TODO
 * @Author H.
 * @Date 2023/5/31 19:02
 * @Version 1.0
 */
@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam(value = "版块Id") @RequestParam(value = "boardId") @NonNull Long boardId,
                            @ApiParam(value = "帖子标题") @RequestParam(value = "title") @NonNull String title,
                            @ApiParam(value = "帖子内容") @RequestParam(value = "content") @NonNull String  content){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否为禁言
        if(user.getState() == 1) {
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //判断板块是否被禁言
        Board board = boardService.selectById(boardId);
        if(board == null || board.getState() == 1 ) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);
        articleService.create(article);
        log.info("发帖成功, userId = " + user.getId());
        //更新session
        user.setArticleCount(user.getArticleCount() + 1);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

//    @ApiOperation("查询所有帖子")
//    @GetMapping("/selectAll")
//    public AppResult<List<Article>> selectAll(){
//        List<Article> articles = articleService.selectAll();
//        return AppResult.success(articles);
//    }

    @ApiOperation("根据版块Id查询帖⼦列表")
    @GetMapping("/selectByBoardId")
    public AppResult<List<Article>> selectByBoardId(@ApiParam(value = "版块Id") @RequestParam(value = "boardId", required = false) Long boardId){
       List<Article> result = null;
        if(boardId == null){
            result = articleService.selectAll();
            log.info("查询所有帖子");
        }else {
          result = articleService.selectByBoardId(boardId);
            log.info("按照版块Id去查询帖子");
        }
        return AppResult.success(result);
    }

    @ApiOperation("根据帖子id获取帖子详情")
    @GetMapping("/getById")
    public AppResult<Article> getById(HttpServletRequest request,
            @ApiParam(value = "帖子Id")  @RequestParam(value = "id")@NotNull Long id){
        //先获取当前登录的用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //获取帖子信息
        Article article = articleService.selectDetailById(id);
        if(user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }

    /**
     * 更新帖子
     * @param id 帖子id
     * @param content 帖子内容
     * @return
     */
    @ApiOperation("编辑帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NotNull Long id,
                            @ApiParam("帖子内容") @RequestParam("content") @NotNull String content){
        //校验帖子作者与登录用户是否同一个人
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.toString());
        }
        //校验是否同一个人
        Article article = articleService.selectById(id);
        if(article == null || article.getState() == 1 || article.getDeleteState() == 1){
            return AppResult.failed("帖子不存在或状态异常");
        }
        if(article.getUserId() != user.getId()){
            return AppResult.failed("只能修改自己发布的帖子");
        }
        articleService.modify(id, content);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @GetMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam("id") @NotNull Long id){
        //校验帖子作者与登录用户是否同一个人
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户状态
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.toString());
        }
        //校验是否同一个人
        Article article = articleService.selectById(id);
        if(article == null|| article.getDeleteState() == 1){
            return AppResult.failed("帖子不存在");
        }
        if(article.getUserId() != user.getId()){
            return AppResult.failed("只能删除自己发布的帖子");
        }
        articleService.deleteById(id);
        //更新session
        user.setArticleCount(user.getArticleCount() - 1);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

    @ApiOperation("根据用户Id查询帖⼦列表")
    @GetMapping("/selectByUserId")
    public AppResult<List<Article>> selectByUserId(HttpServletRequest request,
            @ApiParam(value = "用户Id") @RequestParam(value = "userId" ,required = false ) Long userId){
        List<Article> result = null;
        if(userId == null){
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            result = articleService.selectByUserId(user.getId());
        }else {
            result = articleService.selectByUserId(userId);
        }
          return AppResult.success(result);
    }

    @ApiOperation("文章点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUpById(HttpServletRequest request,
                            @ApiParam(value = "帖子Id") @RequestParam(value = "id") @NonNull Long id){
        //判断当前用户是否被禁言
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() != 0){
            // 日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //调用service方法
        articleService.thumbsUpById(id);
        return AppResult.success();
    }
}